<template>
  <div class="business-management">
    <!-- 主要内容区域 -->
    <div class="main-content-wrapper">
      <el-card>
        <!-- 顶部操作栏 -->
        <div class="top-actions">
          <el-button type="primary" @click="handleAddBusiness">新建商机</el-button>
        </div>

        <!-- 搜索区域 -->
        <el-form :model="searchForm" class="search-form" label-width="80px">
          <el-row :gutter="20" align="middle">
            <el-col :span="6">
              <el-form-item label="商机ID" inline>
                <el-input
                  v-model="searchForm.businessId"
                  placeholder="请输入商机ID"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户姓名" inline>
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入客户姓名"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" inline>
                <el-input
                  v-model="searchForm.phone"
                  placeholder="请输入手机号"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商机状态" inline>
                <el-select
                  v-model="searchForm.status"
                  placeholder="请选择"
                  style="width: 180px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="待分配" value="1" />
                  <el-option label="待跟进" value="2" />
                  <el-option label="跟进中" value="3" />
                  <el-option label="回收" value="4" />
                  <el-option label="转客户" value="5" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="归属人" inline>
                <el-input
                  v-model="searchForm.assignName"
                  placeholder="请输入商机归属人"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleSearch"
                  style="margin-right: 10px"
                  >搜索</el-button
                >
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 商机表格容器 -->
        <div class="table-container">
          <el-table
            :data="businessList"
            stripe
            style="width: 100%; min-width: 1400px; font-size: 14px; table-layout: fixed;"
            :header-cell-style="{ 'font-size': '14px', padding: '10px 12px' }"
          >
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column prop="id" label="商机ID" width="100" />
          <el-table-column prop="name" label="客户姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="150" />
          <el-table-column prop="subject" label="意向学科" width="180">
            <template #default="{ row }">
              <el-tag size="small">
                {{ getSubjectText(row.subject) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assignName" label="归属人" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="status" label="商机状态" width="100">
            <template #default="{ row }">
              {{ getStatusText(row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="nextTime" label="下次跟进时间" width="180" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <!-- 移除权限控制，显示所有操作按钮 -->
              <el-button
                type="primary"
                size="small"
                @click="handleAssign(row)"
                style="margin-right: 5px"
                >分配</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="handleTrack(row)"
                style="margin-right: 5px"
                >跟进</el-button
              >
              <el-button
                type="warning"
                size="small"
                @click="handleBackToPool(row)"
                style="margin-right: 5px"
                >踢回公海</el-button
              >
              <el-button
                type="success"
                size="small"
                @click="handleToCustomer(row)"
                >转客户</el-button
              >
            </template>
          </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新建商机对话框 -->
    <el-dialog
      v-model="addVisible"
      title="添加商机"
      width="600px"
      @close="handleCloseAdd"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="addForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="addForm.gender" placeholder="请选择">
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input v-model="addForm.age" placeholder="请输入年龄" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="addForm.wechat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ">
              <el-input v-model="addForm.qq" placeholder="请输入QQ" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="意向学科">
              <el-select v-model="addForm.subject" placeholder="请选择">
                <el-option label="ai智能应用开发(java)" value="1" />
                <el-option label="ai大模型开发(python)" value="2" />
                <el-option label="ai鸿蒙开发" value="3" />
                <el-option label="ai大数据" value="4" />
                <el-option label="ai嵌入式" value="5" />
                <el-option label="ai测试" value="6" />
                <el-option label="ai运维" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道来源">
              <el-select v-model="addForm.channel" placeholder="请选择">
                <el-option label="线上活动" value="1" />
                <el-option label="线下活动" value="2" />
                <el-option label="自然咨询" value="3" />
                <el-option label="推荐" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历">
              <el-select v-model="addForm.degree" placeholder="请选择">
                <el-option label="初中" value="1" />
                <el-option label="高中" value="2" />
                <el-option label="中专" value="3" />
                <el-option label="大专" value="4" />
                <el-option label="本科" value="5" />
                <el-option label="硕士" value="6" />
                <el-option label="博士" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在职状态">
              <el-select v-model="addForm.jobStatus" placeholder="请选择">
                <el-option label="在职中" value="1" />
                <el-option label="待业" value="2" />
                <el-option label="学生" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="addForm.remark" placeholder="备注信息，最多50字" type="textarea" :rows="2" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseAdd">取消</el-button>
        <el-button type="primary" @click="handleSubmitAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配商机对话框 -->
    <el-dialog
      v-model="assignVisible"
      title="分配商机"
      width="400px"
      @close="handleCloseAssign"
    >
      <el-form :model="assignForm" ref="assignFormRef" :rules="assignRules">
        <el-form-item label="请选择人员" prop="userId">
          <el-select v-model="assignForm.userId" placeholder="请选择人员">
            <el-option label="张晓明" value="22" />
            <el-option label="李艳艳" value="26" />
            <el-option label="王大为" value="23" />
            <el-option label="赵敏" value="24" />
            <el-option label="陈强" value="25" />
            <el-option label="刘佳" value="27" />
            <el-option label="周健" value="28" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseAssign">取消</el-button>
        <el-button type="primary" @click="handleSubmitAssign">确定</el-button>
      </template>
    </el-dialog>

    <!-- 跟进商机对话框 -->
    <el-dialog
      v-model="trackVisible"
      :title="`跟进商机(商机ID:${selectedBusiness?.id})`"
      width="800px"
      @close="handleCloseTrack"
    >
      <el-form
        :model="trackForm"
        ref="trackFormRef"
        :rules="trackRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="trackForm.phone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户姓名">
              <el-input v-model="trackForm.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="trackForm.gender" disabled>
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input v-model="trackForm.age" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="trackForm.wechat" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ">
              <el-input v-model="trackForm.qq" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="意向学科">
              <el-select v-model="trackForm.subject" disabled>
                <el-option 
                  v-for="(label, value) in subjectMap" 
                  :key="value" 
                  :label="label" 
                  :value="value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属课程">
              <el-select v-model="trackForm.courseId" disabled>
                <el-option label="SpringAI模型应用开发" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历">
              <el-select v-model="trackForm.degree" disabled>
                <el-option 
                  v-for="(label, value) in degreeMap" 
                  :key="value" 
                  :label="label" 
                  :value="value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在职状态">
              <el-select v-model="trackForm.jobStatus" disabled>
                <el-option 
                  v-for="(label, value) in jobStatusMap" 
                  :key="value" 
                  :label="label" 
                  :value="value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道来源">
              <el-select v-model="trackForm.channel" disabled>
                <el-option 
                  v-for="(label, value) in channelMap" 
                  :key="value" 
                  :label="label" 
                  :value="value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="trackForm.remark" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 跟进信息 -->
        <div class="track-info-section">
          <h4>跟进信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="跟进状态" prop="trackStatus">
                <el-select v-model="trackForm.trackStatus" placeholder="请选择">
                  <el-option label="接通" value="1" />
                  <el-option label="未接通" value="2" />
                  <el-option label="拒绝" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="沟通重点" prop="keyItems">
                <el-select v-model="trackForm.keyItems" placeholder="请选择" multiple collapse-tags>
                  <el-option label="价格" value="价格" />
                  <el-option label="课程" value="课程" />
                  <el-option label="位置" value="位置" />
                  <el-option label="师资" value="师资" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下次跟进" prop="nextTime">
                <el-date-picker
                  v-model="trackForm.nextTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="沟通纪要" prop="record">
                <el-input v-model="trackForm.record" placeholder="请输入沟通纪要" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseTrack">取消</el-button>
        <el-button type="primary" @click="handleSubmitTrack">确定</el-button>
      </template>
    </el-dialog>

    <!-- 踢回公海确认对话框 -->
    <el-dialog
      v-model="backToPoolVisible"
      title="提示"
      width="400px"
      :show-close="false"
    >
      <div style="text-align: center; padding: 20px 0;">
        <p>确认将该商机踢回公海吗？</p>
      </div>
      <template #footer>
        <el-button @click="backToPoolVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitBackToPool">确定</el-button>
      </template>
    </el-dialog>

    <!-- 转客户确认对话框 -->
    <el-dialog
      v-model="toCustomerVisible"
      title="提示"
      width="400px"
      :show-close="false"
    >
      <div style="text-align: center; padding: 20px 0;">
        <p>确认将该商机转为客户吗？</p>
      </div>
      <template #footer>
        <el-button @click="toCustomerVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitToCustomer">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { getUserInfo } from "@/utils/auth";

export default {
  name: "BusinessManagement",
  setup() {
    // 从用户信息中获取角色
    const getUserRole = () => {
      const userInfo = getUserInfo();
      // 添加调试信息
      console.log('用户信息:', userInfo);
      // 确保返回正确的角色，区分business_operator和clue_operator
      if (userInfo && userInfo.role) {
        console.log('获取到的角色:', userInfo.role);
        return userInfo.role;
      }
      // 默认返回空字符串，避免未登录时显示操作按钮
      console.log('未获取到角色信息，返回空');
      return '';
    };
    const userRole = ref(getUserRole());

    // 搜索表单
    const searchForm = reactive({
      businessId: "",
      name: "",
      phone: "",
      status: "",
      assignName: ""
    });

    // 商机列表数据
    const businessList = ref([]);

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 新建商机相关
    const addVisible = ref(false);
    const addFormRef = ref(null);
    const addForm = reactive({
      name: "",
      phone: "",
      gender: "",
      age: "",
      wechat: "",
      qq: "",
      subject: "",
      channel: "",
      degree: "",
      jobStatus: "",
      remark: ""
    });
    const addRules = {
      name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
      ]
    };

    // 分配商机相关
    const assignVisible = ref(false);
    const assignFormRef = ref(null);
    const assignForm = reactive({ userId: "" });
    const assignRules = {
      userId: [{ required: true, message: '请选择人员', trigger: 'change' }]
    };
    const currentAssignBusinessId = ref(null);

    // 跟进商机相关
    const trackVisible = ref(false);
    const trackFormRef = ref(null);
    const trackForm = reactive({
      id: "",
      name: "",
      phone: "",
      gender: "",
      age: "",
      wechat: "",
      qq: "",
      subject: "",
      courseId: "",
      degree: "",
      jobStatus: "",
      channel: "",
      remark: "",
      status: "",
      userId: "",
      trackStatus: "",
      keyItems: [],
      nextTime: null,
      record: ""
    });
    const trackRules = {
      trackStatus: [{ required: true, message: '请选择跟进状态', trigger: 'change' }],
      keyItems: [{ required: true, message: '请选择沟通重点', trigger: 'change' }],
      nextTime: [{ required: true, message: '请选择下次跟进时间', trigger: 'change' }],
      record: [{ required: true, message: '请输入沟通纪要', trigger: 'blur' }]
    };
    const selectedBusiness = ref(null);

    // 踢回公海相关
    const backToPoolVisible = ref(false);
    const currentBackToPoolBusinessId = ref(null);

    // 转客户相关
    const toCustomerVisible = ref(false);
    const currentToCustomerBusinessId = ref(null);

    // 映射关系
    const subjectMap = {
      1: "ai智能应用开发(java)",
      2: "ai大模型开发(python)",
      3: "ai鸿蒙开发",
      4: "ai大数据",
      5: "ai嵌入式",
      6: "ai测试",
      7: "ai运维",
    };

    const channelMap = {
      1: "线上活动",
      2: "线下活动",
      3: "自然咨询",
      4: "推荐",
    };

    const degreeMap = {
      1: "初中",
      2: "高中",
      3: "中专",
      4: "大专",
      5: "本科",
      6: "硕士",
      7: "博士",
    };

    const jobStatusMap = {
      1: "在职中",
      2: "待业",
      3: "学生",
    };

    // 获取意向学科文本
    const getSubjectText = (subject) => {
      return subjectMap[subject] || "未知";
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        1: "待分配",
        2: "待跟进",
        3: "跟进中",
        4: "回收",
        5: "转客户",
      };
      return statusMap[status] || "未知";
    };

    // 获取商机列表
    const getBusinessList = async () => {
      try {
        const params = {
          ...searchForm,
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
        };

        // 移除空值参数
        Object.keys(params).forEach((key) => {
          if (
            params[key] === "" ||
            params[key] === null ||
            params[key] === undefined
          ) {
            delete params[key];
          }
        });

        // 调用接口获取数据
        const response = await axios.get("/api/businesses", {
          params: params,
        });

        const result = response.data;

        if (result.code === 1) {
          businessList.value = result.data.rows || [];
          pagination.total = Number(result.data.total) || 0;
        } else {
          ElMessage.error(result.msg || "获取商机列表失败");
        }
      } catch (error) {
        console.error("获取商机列表异常:", error);
        ElMessage.error("获取商机列表失败，请稍后重试");
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      getBusinessList();
    };

    // 重置
    const handleReset = () => {
      Object.keys(searchForm).forEach((key) => {
        searchForm[key] = "";
      });
      pagination.currentPage = 1;
      getBusinessList();
    };

    // 分页大小改变
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      getBusinessList();
    };

    // 当前页改变
    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      getBusinessList();
    };

    // 新建商机
    const handleAddBusiness = () => {
      // 重置表单
      Object.keys(addForm).forEach((key) => {
        addForm[key] = "";
      });
      if (addFormRef.value) {
        addFormRef.value.resetFields();
      }
      addVisible.value = true;
    };

    // 提交新建商机
    const handleSubmitAdd = async () => {
      if (!addFormRef.value) return;
      
      try {
        await addFormRef.value.validate();
        
        // 调用添加接口
        const response = await axios.post("/api/businesses", addForm);
        const result = response.data;
        
        if (result.code === 1) {
          ElMessage.success("添加商机成功");
          addVisible.value = false;
          getBusinessList();
        } else {
          ElMessage.error(result.msg || "添加商机失败");
        }
      } catch (error) {
        console.error("添加商机异常:", error);
        if (error.name !== 'ValidationError') {
          ElMessage.error("添加商机失败，请稍后重试");
        }
      }
    };

    // 关闭新建对话框
    const handleCloseAdd = () => {
      addVisible.value = false;
    };

    // 分配商机
    const handleAssign = (row) => {
      currentAssignBusinessId.value = row.id;
      assignForm.userId = "";
      if (assignFormRef.value) {
        assignFormRef.value.resetFields();
      }
      assignVisible.value = true;
    };

    // 提交分配
    const handleSubmitAssign = async () => {
      if (!assignFormRef.value || !currentAssignBusinessId.value) return;
      
      try {
        await assignFormRef.value.validate();
        
        // 调用分配接口
        const response = await axios.put(`/api/businesses/assign/${currentAssignBusinessId.value}/${assignForm.userId}`);
        const result = response.data;
        
        if (result.code === 1) {
          ElMessage.success("分配商机成功");
          assignVisible.value = false;
          getBusinessList();
        } else {
          ElMessage.error(result.msg || "分配商机失败");
        }
      } catch (error) {
        console.error("分配商机异常:", error);
        if (error.name !== 'ValidationError') {
          ElMessage.error("分配商机失败，请稍后重试");
        }
      }
    };

    // 关闭分配对话框
    const handleCloseAssign = () => {
      assignVisible.value = false;
      currentAssignBusinessId.value = null;
    };

    // 跟进商机
    const handleTrack = async (row) => {
      try {
        // 调用根据ID查询接口
        const response = await axios.get(`/api/businesses/${row.id}`);
        const result = response.data;
        
        if (result.code === 1) {
          selectedBusiness.value = result.data;
          // 填充跟进表单
          const data = result.data;
          Object.assign(trackForm, {
            id: data.id,
            name: data.name,
            phone: data.phone,
            gender: data.gender,
            age: data.age,
            wechat: data.wechat,
            qq: data.qq,
            subject: data.subject,
            courseId: data.courseId,
            degree: data.degree,
            jobStatus: data.jobStatus,
            channel: data.channel,
            remark: data.remark,
            status: data.status,
            userId: data.userId,
            trackStatus: "",
            keyItems: [],
            nextTime: null,
            record: ""
          });
          trackVisible.value = true;
        } else {
          ElMessage.error(result.msg || "获取商机详情失败");
        }
      } catch (error) {
        console.error("获取商机详情异常:", error);
        ElMessage.error("获取商机详情失败，请稍后重试");
      }
    };

    // 提交跟进
    const handleSubmitTrack = async () => {
      if (!trackFormRef.value) return;
      
      try {
        await trackFormRef.value.validate();
        
        // 调用跟进接口
        const response = await axios.put("/api/businesses", trackForm);
        const result = response.data;
        
        if (result.code === 1) {
          ElMessage.success("跟进商机成功");
          trackVisible.value = false;
          getBusinessList();
        } else {
          ElMessage.error(result.msg || "跟进商机失败");
        }
      } catch (error) {
        console.error("跟进商机异常:", error);
        if (error.name !== 'ValidationError') {
          ElMessage.error("跟进商机失败，请稍后重试");
        }
      }
    };

    // 关闭跟进对话框
    const handleCloseTrack = () => {
      trackVisible.value = false;
      selectedBusiness.value = null;
    };

    // 踢回公海
    const handleBackToPool = (row) => {
      currentBackToPoolBusinessId.value = row.id;
      backToPoolVisible.value = true;
    };

    // 提交踢回公海
    const handleSubmitBackToPool = async () => {
      if (!currentBackToPoolBusinessId.value) return;
      
      try {
        // 调用踢回公海接口
        const response = await axios.put(`/api/businesses/back/${currentBackToPoolBusinessId.value}`);
        const result = response.data;
        
        if (result.code === 1) {
          ElMessage.success("踢回公海成功");
          backToPoolVisible.value = false;
          getBusinessList();
        } else {
          ElMessage.error(result.msg || "踢回公海失败");
        }
      } catch (error) {
        console.error("踢回公海异常:", error);
        ElMessage.error("踢回公海失败，请稍后重试");
      }
    };

    // 转客户
    const handleToCustomer = (row) => {
      currentToCustomerBusinessId.value = row.id;
      toCustomerVisible.value = true;
    };

    // 提交转客户
    const handleSubmitToCustomer = async () => {
      if (!currentToCustomerBusinessId.value) return;
      
      try {
        // 调用转客户接口
        const response = await axios.post(`/api/businesses/toCustomer/${currentToCustomerBusinessId.value}`);
        const result = response.data;
        
        if (result.code === 1) {
          ElMessage.success("转为客户成功");
          toCustomerVisible.value = false;
          getBusinessList();
        } else {
          ElMessage.error(result.msg || "转为客户失败");
        }
      } catch (error) {
        console.error("转为客户异常:", error);
        ElMessage.error("转为客户失败，请稍后重试");
      }
    };

    // 组件挂载时获取数据
    onMounted(() => {
      // 重新获取用户角色信息，确保权限控制准确
      userRole.value = getUserRole();
      getBusinessList();
    });

    return {
      userRole,
      searchForm,
      businessList,
      pagination,
      addVisible,
      addFormRef,
      addForm,
      addRules,
      assignVisible,
      assignFormRef,
      assignForm,
      assignRules,
      trackVisible,
      trackFormRef,
      trackForm,
      trackRules,
      selectedBusiness,
      backToPoolVisible,
      toCustomerVisible,
      subjectMap,
      channelMap,
      degreeMap,
      jobStatusMap,
      getSubjectText,
      getStatusText,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAddBusiness,
      handleSubmitAdd,
      handleCloseAdd,
      handleAssign,
      handleSubmitAssign,
      handleCloseAssign,
      handleTrack,
      handleSubmitTrack,
      handleCloseTrack,
      handleBackToPool,
      handleSubmitBackToPool,
      handleToCustomer,
      handleSubmitToCustomer,
    };
  },
};
</script>

<style scoped>
.business-management {
  padding: 20px;
  overflow-x: visible;
}

.main-content-wrapper {
  overflow-x: scroll;
  width: 100%;
  min-width: 100%;
  margin-bottom: 5px;
}

.el-table {
  width: 100%;
  min-width: 1400px;
  table-layout: auto;
}

.top-actions {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.track-info-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.track-info-section h4 {
  margin-bottom: 16px;
  color: #303133;
  font-weight: 600;
}

.table-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 16px;
}

/* 页面级滚动条样式 - 更粗更明显 */
::-webkit-scrollbar {
  width: 14px;
  height: 14px;
  display: block;
}

::-webkit-scrollbar-track {
  background: #e0e0e0;
  border-radius: 7px;
}

::-webkit-scrollbar-thumb {
  background: #999;
  border-radius: 7px;
  border: 3px solid #e0e0e0;
}

::-webkit-scrollbar-thumb:hover {
  background: #777;
}

/* 确保水平滚动条始终可见 */
::-webkit-scrollbar-horizontal {
  display: block;
}

/* Firefox滚动条样式 */
html {
  scrollbar-width: thick;
  scrollbar-color: #999 #e0e0e0;
}

/* 优化表格单元格样式，防止内容溢出 */
.table-container .el-table__cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
